package pers.zxk.jlytnews.servlet;

import pers.zxk.jlytnews.base.BaseServlet;
import pers.zxk.jlytnews.manager.UserStateManager;
import pers.zxk.jlytnews.util.CommonUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.IOException;

public class ImageServlet extends BaseServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //判断用户是否登录
        if(!UserStateManager.isLogin(req)){
            CommonUtil.sendJsonData(resp, null, 1, "请先登录！");
            return;
        }

        //eg.浏览器传过来的地址为：http://localhost:8080/uploads/images/201023140521.jpg?type=zxk
        //String method = req.getServletPath();//  /uploads/images
        //String requestURI = req.getRequestURI();  /uploads/images/201023140521.jpg
        //String type = req.getParameter("type"); zxk
        String requestURL = req.getRequestURL().toString(); //完整地址 不含参数

        //todo 其他格式设置


        resp.setContentType("image/jpeg");

        String realPath = CommonUtil.urlToPath(requestURL);
        BufferedInputStream in = new BufferedInputStream(new FileInputStream(realPath));
        byte[] content = new byte[in.available()];
        in.read(content);
        in.close();
        BufferedOutputStream out = new BufferedOutputStream(resp.getOutputStream());
        out.write(content);
        out.close();
    }
}
